package controller;

import common.Message;
import common.MessageType;
import common.StuMidClass;
import common.User;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import ui.Main;
import util.FlushCourse;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;


public class AddStuController {
    private Socket socket= Main.userClientService.getSocket();
    private String courseid;
    private TeacherCourseController teacherCourseController;
    private ObservableList<User> user;
    public AddStuController(ObservableList<User> user,String courseid,TeacherCourseController teacherCourseController) {
        this.user=user;
        this.courseid = courseid;
        this.teacherCourseController=teacherCourseController;
    }
    @FXML
    private TextField name;
    @FXML
    private TextField number;
    @FXML
    private Label error;
    @FXML
    public void add(){
        if(number.getText().equals(Main.userClientService.getUser().getNumber())){
            error.setText("无法添加自己");
            return;
        }
        error.setText("");
        Message ms=new Message();
        ms.setState(MessageType.Stu_Add);
        try {
            ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(ms);
            StuMidClass stuMidClass=new StuMidClass(name.getText(),number.getText(),courseid);
            oos.writeObject(stuMidClass);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            Stage stage=(Stage) name.getScene().getWindow();
            new Thread(()->{
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    System.out.println("刷新学生列失败");
                }
                Platform.runLater(() -> {
                    teacherCourseController.flush(FlushCourse.studentMap.get(courseid));
                    System.out.println("刷新学生列表");
                });
            }).start();
            stage.close();
        }
    }
}
